#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: sparql.py
# Author: Tomás Vírseda
# License: GPL v3
# Description:  an advance SPARQL Query Editor

import datetime

import gtk
import pango

from vazaarlib.ui.widgets.genericlistview import GenericListView
from vazaarlib.utils import get_logger
from vazaarlib.namespaces import *

class SPARQLEditor:
    """ SPARQL Editor """

    def __init__(self, gui):
        self.gui = gui
        self.log = get_logger("SPARQLEditor")

        self.gui.frontend['qname'] = self.gui.glade.widgets.get_widget("etyQueryName")
        self.gui.frontend['query'] = self.gui.glade.widgets.get_widget("txtQuery")
        self.gui.frontend['qexec'] = self.gui.glade.widgets.get_widget("btnExecQuery")
        self.gui.frontend['qsave'] = self.gui.glade.widgets.get_widget("btnSaveQuery")
        self.gui.frontend['qadd'] = self.gui.glade.widgets.get_widget("btnAddQuery")
        self.gui.frontend['qdel'] = self.gui.glade.widgets.get_widget("btnDelQuery")
        self.gui.frontend['qresult'] = self.gui.glade.widgets.get_widget("lblSparqlResult")
        self.gui.frontend['sparqlraw'] = self.gui.glade.widgets.get_widget("RawContainer")

        font = pango.FontDescription("Monospace 10")
        self.gui.frontend['query'].modify_font(font)
        self.gui.frontend['connections'] = {
            'btnExecQuery/clicked':     self.exec_query,
        }

        #connect signals
        for wid_con, func in self.gui.frontend['connections'].iteritems():
            wid,con = wid_con.split('/')
            self.gui.glade[wid].connect(con,func)

        self.setup()

    def setup(self):
        text = "<b>The following namespaces are added automatically</b>:\n\n"
        for ns in NSBINDINGS:
            text += '<b>%-05s:\t</b>' % ns + NSBINDINGS[ns] + '\r\n'
        self.gui.frontend['query'].set_tooltip_markup(text)

    def item_activated(self, listview, path, view_column, *user_data):
        selection = listview.get_selection()
        model, selected = selection.get_selected_rows()
        path = selected[0]
        iter = model.get_iter_from_string(str(path[0]))
        id = model.get_value(iter, 1)
        self.gui.actions.display_resource(id)

    def exec_query(self, widget, data=None):
        dstart = datetime.datetime.now()
        bufin = self.gui.frontend['query'].get_buffer()
        start = bufin.get_start_iter()
        end = bufin.get_end_iter()
        query_body = bufin.get_text(start, end)
        query_header = ''
        for ns in NSBINDINGS:
            query_header += 'PREFIX ' + ns + ': <' + NSBINDINGS[ns] + '>\n'
        query = query_header + query_body

        try:
            result = self.gui.ask.this(query)
            ncols = len(result.selectionF)
            if ncols > 1:
                columns = {}
                columns[0] = ('Record', gtk.CellRendererText())
                for i in xrange(ncols):
                    columns[i+1] = (result.selectionF[i], gtk.CellRendererText())
                rawview = GenericListView(columns)
                rawview.connect('row-activated', self.item_activated)
                firstcol = rawview.get_column(0)
                firstcol.set_visible(True)
                i = 1
                for data in result.selected:
                    list = []
                    record = "%06d" % i
                    list.append(record)
                    for item in data:
                        list.append(item)
                    i = i + 1
                    rawview.add(list)
            else:
                columns = {}
                columns[0] = ('Record', gtk.CellRendererText())
                columns[1] = (result.selectionF[0], gtk.CellRendererText())

                rawview = GenericListView(columns)
                rawview.connect('row-activated', self.item_activated)

                list = []
                i = 1
                for item in result.selected:
                    record = "%06d" % i
                    list.append((record, item))
                    i = i + 1
                rawview.addList(list)

            dend = datetime.datetime.now()
            self.gui.frontend['qresult'].set_markup("<b>Results:</b> %d resources. Query executed in <i>%s</i> seconds" % (len(result.selected), (dend - dstart)))
        except Exception, error:
            self.log.debug(error)
            rawview = gtk.TextView()
            data = str(error)
            bufout = rawview.get_buffer()
            bufout.set_text(data)
            rawview.set_buffer(bufout)


        old = self.gui.frontend['sparqlraw'].get_children()
        if old:
            self.gui.frontend['sparqlraw'].remove(old[0])
        font = pango.FontDescription("Monospace 10")
        rawview.modify_font(font)
        container = gtk.ScrolledWindow()
        container.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        container.add(rawview)
        self.gui.frontend['sparqlraw'].add(container)
        self.gui.frontend['sparqlraw'].show_all()
